package com.plpm.plugin.impl;

import com.alibaba.fastjson2.JSON;
import com.plpm.common.model.DataHandlerModel;
import com.plpm.common.model.PluginInfo;
import com.plpm.common.model.ProtocolParam;
import com.plpm.plugin.DataProcessor;
import org.slf4j.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Map;

/**
 * @author RAN
 * @data 2025/4/14 15:55
 * @Description: 插件实现类
 */
public class DataProcessorImpl implements DataProcessor {

    private Logger log = null;

    @Override
    public void setLog(Logger logger) {
        this.log = logger;
    }

    @Override
    public PluginInfo registry(String configPath) {
        log.info("开始注册插件, 解析PluginInfo.json文件");
        File file = new File(configPath);
        if (!file.exists()) {
            throw new RuntimeException("未获取到配置文件");
        }
        try {
            String json = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
            return JSON.parseObject(json, PluginInfo.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, double[]> process(DataHandlerModel dataHandlerModel) {
        log.info("开始执行process方法");
        Map<String, double[]> data = dataHandlerModel.getData();
        if (dataHandlerModel.getProtocolParam().getMode() == 0) {
            return data;
        }
        ProtocolParam protocolParam = dataHandlerModel.getProtocolParam();
        double[] values = data.get(dataHandlerModel.getYParam());
        for (int i = 0; i < values.length; i++) {
            // 将float转换为int以进行位操作
            int value = (int) values[i];
            // 计算需要提取的位数
            int bitLength = protocolParam.getStopBit() - protocolParam.getStartBit();
            // 创建掩码
            int mask = (1 << bitLength) - 1;
            // 右移并应用掩码以提取指定位
            int extractedBits = (value >> protocolParam.getStartBit()) & mask;
            // 与validValue比较
            values[i] = (extractedBits == protocolParam.getValidValue()) ? 1 : 0;
        }
        data.put(dataHandlerModel.getYParam(), values);
        return data;
    }
}
